package TaskStructure
{
	import flash.display.Sprite;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.events.IOErrorEvent;
	
	public class LogWriter extends Sprite
	{
		private var filename:String;
		
		public function LogWriter(filename:String)
		{
			this.filename = filename
			var file:File = File.applicationStorageDirectory.resolvePath(String(filename+".txt"));
			try 
			{
				var stream:FileStream = new FileStream();
				if (file.exists)
				{
					stream.openAsync(file, FileMode.APPEND);
				} else
				{
					stream.openAsync(file, FileMode.WRITE);
					stream.writeUTFBytes(LogEvent.TOSTRING()+File.lineEnding);
				}
				
			} catch (e:IOErrorEvent) 
			{
				this.dispatchEvent(new IOErrorEvent(e.type));		
			}
			stream.close();
		}
		/** Add a new line of text ended with an end line symbol. */
		public function addNewLine(str:String):void
		{
			//var file:File = File.applicationStorageDirectory.resolvePath(String("userfiles/"+filename+".txt"));
			var file:File = File.applicationStorageDirectory.resolvePath(String(filename+".txt"));
			try 
			{
				var stream:FileStream = new FileStream(); 
				stream.openAsync(file, FileMode.APPEND);
				
			} catch (e:IOErrorEvent) 
			{
				this.dispatchEvent(new IOErrorEvent(e.type));		
			}
			stream.writeUTFBytes(String(str+File.lineEnding));
			stream.close();
		}
	}
}